package com.zbkj.service.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zbkj.common.model.project.ProjectParamJun;
import com.zbkj.service.dao.project.ProjectParamJunMapper;
import com.zbkj.service.service.project.ProjectParamJunService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 项目参数军标表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-10-07
 */
@Service
public class ProjectParamJunServiceImpl extends ServiceImpl<ProjectParamJunMapper, ProjectParamJun> implements ProjectParamJunService {

    @Override
    public ProjectParamJun getParamJun(Long projectId, Integer ptype) {
        if(Objects.isNull(projectId) || Objects.isNull(ptype)) {
            return null;
        }
        LambdaQueryWrapper<ProjectParamJun> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectParamJun::getDeleteFlag,0)
                .eq(ProjectParamJun::getProjectId,projectId)
                .eq(ProjectParamJun::getPtype,ptype)
                .last(" limit 1");
        return this.getOne(wrapper,false);
    }

    @Override
    public List<ProjectParamJun> getParamJunList(Long projectId) {
        if(Objects.isNull(projectId)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<ProjectParamJun> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectParamJun::getDeleteFlag,0)
                .eq(ProjectParamJun::getProjectId,projectId);
        return this.list(wrapper);
    }

    @Override
    public ProjectParamJun getParamJunByQueryType(int queryType, Long projectId) {
        if(Objects.isNull(projectId)) {
            return null;
        }
        if(queryType == 0) {
            return this.getParamJun(projectId, 0);
        } else if(queryType == 1) {
            return this.getParamJun(projectId, 1);
        } else {
            List<ProjectParamJun> paramList = getParamJunList(projectId);
            if(CollectionUtils.isEmpty(paramList)) {
                return null;
            }
            ProjectParamJun param = paramList.stream().filter(v->v.getPtype() == 1).findFirst().orElse(null);
            return Objects.nonNull(param) ? param : paramList.stream().filter(v->v.getPtype() == 0).findFirst().orElse(null);
        }
    }

    @Override
    public boolean paramSaveFromAdmin(Long projectId, ProjectParamJun paramJun) {
        ProjectParamJun paramJunDb = getParamJun(projectId,1);
        paramJun.setProjectId(projectId);
        paramJun.setPtype(1);
        if(Objects.isNull(paramJunDb)) {
            return this.save(paramJun);
        } else {
            paramJun.setId(paramJunDb.getId());
            return this.updateById(paramJun);
        }
    }
}
